import { useRef, useCallback, useState } from "react";
import { useAutoResizeTextArea } from "@/hooks";
import { useNavigate } from "react-router-dom";
import { Button, Upload, Tag } from "@arco-design/web-react";
import { IconToTop, IconSend } from "@arco-design/web-react/icon";
import ChatApi from "@/api/chat/chat-api.ts";
import styles from "./index.module.less";
// import CommonApi from "@/api/common/common-api.ts";
const HomeChat = () => {
  const userQuestion = useRef<string>("");
  const textareaRef = useAutoResizeTextArea(350);
  const navigate = useNavigate();
  const [uploadFileList, setUploadFileList] = useState<Array<any>>([]);
  const [uplodaLoading, setUplodaLoading] = useState<boolean>(false);

  const createChat = () => {
    createOrUpdateSessionRecordFn();
  };

  // 创建会话
  const createOrUpdateSessionRecordFn = async () => {
    try {
      let res = await ChatApi.createOrUpdateSessionRecord({
        requestId: "",
        name: "",
      });
      if (res.code === 200) {
        let requestId = res.result;
        navigate(`/chat/${requestId}`, {
          state: {
            userQuestion: userQuestion.current,
            // fileId: uploadFile?.result?.fileId,
            files: uploadFileList,
          },
        });
      }
      console.log(res);
    } catch (error) {
      console.log(error);
    }
  };
  // 问答
  const handlerChangeTextArea = useCallback((e: any) => {
    let textareaValue = e.target.value;
    userQuestion.current = textareaValue;
  }, []);

  // 监听文件上传
  const handlerUpload = (res: any) => {
    if (res[0].status == "done") {
      let upload = res[0];
      if (upload?.response?.code === 200) {
        let fileObj = {
          name: upload.name,
          result: upload.response.result,
        };
        setUplodaLoading(false);
        setUploadFileList((objFileList: any) => {
          return [...objFileList, fileObj];
        });
      }
    }
  };

  // 删除标签
  const handlerTagClose = (data: any) => {
    setUploadFileList((objFileList: any) => {
      let newFileList = objFileList.filter((item: any) => {
        return item?.result?.fileId !== data?.result?.fileId;
      });
      return newFileList;
    });
  };

  return (
    <div className={styles.homeChatWarp}>
      <div className="homeChat">
        <div id="wordDance">
          开启智能编程新时代：用AI的力量，让代码生成变得简单快捷，预览未来，尽在您的指尖。
        </div>
        <div className="textarea_box">
          <textarea
            ref={textareaRef}
            placeholder="请输入您要提问的内容"
            name="111"
            id="chat_textarea"
            onChange={handlerChangeTextArea}
          ></textarea>

          <div className="question_tools">
            {/* 只能上传图片 */}
            <Upload
              accept=".png,.jpg,.jpeg"
              multiple={true}
              className="mr-[20px]"
              onChange={handlerUpload}
              fileList={[]}
              autoUpload
              action="/api/upload/file"
              beforeUpload={() => {
                return new Promise((resolve, reject) => {
                  setUplodaLoading(true);
                  resolve(true);
                });
              }}
            >
              <Button loading={uplodaLoading} icon={<IconToTop />}></Button>
            </Upload>

            {/* <Button icon={<IconToTop />}></Button> */}
            <Button
              type="primary"
              icon={<IconSend />}
              onClick={() => {
                createChat();
              }}
            ></Button>
          </div>
        </div>

        <div className="mt-[5px]">
          {uploadFileList.map((uploadFile: any) => (
            <Tag
              key={uploadFile?.result?.fileId}
              onClose={() => handlerTagClose(uploadFile)}
              style={{ margin: "0 3px", color: "#000" }}
              color="#fff"
              closable
            >
              {uploadFile?.name}
            </Tag>
          ))}
        </div>
      </div>
    </div>
  );
};

export default HomeChat;
